import React from 'react';
import { connect } from 'react-redux';
import { Button, Row, Col, Card, Input, Tooltip } from 'antd';
import CheckList from './list';
import CommonListsIndex from '../../../../components/CommonLists/index';
import services from '../../../../services/api';
import { message } from 'antd';
import Modal from '../../../../components/Modal/index';
import CustomForm from '../../../../components/CustomForm';
import Distribute from '../distribute';
import CodeLabel from '../../../../components/CodeLabel';
import BigFile from 'src/components/Upload/BigFile';
import CaseTrace from '../../TaskCenter/caseTrace';
import StrategyLogs from '../../../../components/StrategyLogs';
import SelectCaseType from './selectCaseType'

const { TextArea } = Input;

function mapStateToProps(state) {
  return {
    risk_level: state.code.risk_level,
  };
}

@connect(mapStateToProps)
class CaseDetail extends CommonListsIndex {
  constructor(props) {
    super(props);
    this.api = 'caseApi';
    this.listsComponent = CheckList;
    this.model_width = '500px';
    this.queryParams = {};
    this.queryPanigation = {
      current_page: 1,
      page_size: 10,
    };
    this.queryTableParams = {};
    this.detailComponent = '/case/check/id/detail';
    this.state = {
      list: [],
      totalCount: 0,
      selectedRowKeys: [],
      case_id: props.match.params.id,
      strategies: [],
      tab: 'tab1',
      variables: {},
      strategyLogs: {},
    };
  }

  componentDidMount() {
    this.getCaseDetail();
  }

  componentWillUnmount() {
    if (this.state.status === 2 && this.state.is_current_user_check) {
      this.props.dispatch({ type: 'pageClose/waringReduce' });
    }
  }

  getCaseDetail = () => {
    services[this.api]
      .getCaseDetail({
        case_id: this.state.case_id,
      })
      .then((res) => {
        if (res.code === 0) {
          this.setState(
            {
              ...res.data,
              list: res.data.strategies,
            },
            this.getStrategyLogs
          );
          if (res.data.status === 2 && res.data.is_current_user_check) {
            this.props.dispatch({ type: 'pageClose/waringAdd' });
          }
        } else {
          message.error(res.msg);
        }
      });
  };

  getStrategyLogs = () => {
    services.caseApi.monitorDetail({ req_id: this.state.request_id }).then((res) => {
      if (res.code === 0) {
        this.setState({ strategyLogs: res.data });
      }
    });
  };

  refreshTableFilter = (params) => {
    this.queryTableParams = { ...this.queryTableParams, ...params };
    this.refreshPanagaition(this.initQueryPanigation);
    this.freshQueryList();
  };

  caseTrace() {
    services.caseTask.caseTrace({ case_id: this.state.case_id }).then((res) => {
      if (res.code === 0) {
        this.setState({ logs: res.data });
      }
    });
  }

  queryList(params) {
    this.setState({
      list: this.state.strategies.filter((item) => {
        return item.strategy_name ? item.strategy_name.match(params.strategy_name) : false;
      }),
    });
  }
  freshQueryList = () => {
    this.queryList({ ...this.queryPanigation, ...this.queryTableParams, ...this.queryParams });
  };
  refreshPanagaition = (params) => {
    this.queryPanigation = {
      ...this.queryPanigation,
      ...params,
    };
  };
  refreshFilter = (params) => {
    this.queryParams = params;
    this.freshQueryList(this.queryParams);
  };

  // 开启分配
  distribute = () => {
    this.form.validateFields((err, values) => {
      if (!err) {
        let params = {
          // case_category_id: this.form.getFieldValue('case_category_id'),
          check_remark: this.form.getFieldValue('check_remark'),
          file_url: this.file || '',
          case_node_id: this.state.case_node_id,
        };
        Modal.open({
          title: '分配审核人员',
          width: this.model_width ? this.model_width : '600px',
          content: (
            <Distribute
              colNum={1}
              closeModal={this.closeModal}
              case_id={this.state.case_id}
              actionType='distribute_and_save'
              event_id={this.state.event_id}
              saveData={params}
              {...this.props}
            />
          ),
          isOkBtn: false,
          maskClosable: false,
          isCancelBtn: false,
        });
      }
    })
  };

  closeModal = (onlyClose) => {
    Modal.close();
    !onlyClose && this.getCaseDetail();
  };

  handleSubmit = (case_category_id) => {
    this.form.validateFields((err, values) => {
      if (!err) {
        const params = {
          case_id: this.state.case_id,
          case_category_id,
          check_remark: values.check_remark,
          file_url: this.file || '',
          case_node_id: this.state.case_node_id,
        };
        services[this.api].endCase(params).then((res) => {
          if (res.code === 0) {
            this.getCaseDetail();
            message.success(res.msg);
          } else {
            message.error(res.msg);
          }
        });
      }
    });
  };

  fileChange = (params) => {
    this.file = params.filePath;
  };

  selectCase = () => {
    this.form.validateFields((err, values) => {
      if (!err) {
        Modal.open({
          title: '结案处理',
          width: '600px',
          content: (
            <SelectCaseType
              {...this.props}
              colNum={1}
              closeModal={this.closeModal}
              handleSubmit={this.handleSubmit}
            />
          ),
          isOkBtn: false,
          maskClosable: false,
          isCancelBtn: false,
        });
      }})
  }

  render() {
    const formItems = [
      {
        label: {
          label: '状态',
        },
        name: 'status',
        component: <span>{this.state.status_name}</span>,
      },
      {
        label: {
          label: '审核意见',
        },
        name: 'check_remark',
        options: {
          initialValue: this.state.check_remark || undefined,
          rules: [
            { required: true, message: '请填写' },
            { max: 256, message: '最长256个字符' },
            { pattern: /\S+/, message: '请输入有效内容' },
          ],
        },
        component: <TextArea rows={4} placeholder='请填写' />,
      },
      {
        label: {
          label: '上传文件',
          extra: '仅支持zip格式，大小限制500M',
        },
        name: 'file_url',
        options: {
          initialValue: '',
        },
        component: (
          <BigFile api='caseTask' fileFormat={['.zip']} index={1} onChange={this.fileChange} />
        ),
      },
    ];

    return (
      <div>
        <Card title='案件详情'>
          <Row style={{ lineHeight: '3' }}>
            <Col span={8}>
              <span>请求ID</span>: {this.state.request_id}
            </Col>
            <Col span={8}>
              <span>发生时间</span>: {this.state.request_time}
            </Col>
            <Col span={8}>
              <span>评估结果</span>: <CodeLabel code={'risk_level'} value={this.state.risk_level} />
            </Col>
            <Col span={8}>
              <span>请求策略</span>: {this.state.hit_strategy_name}
            </Col>
            <Col span={8}>
              <div className="overflowtext">
                <span>处置建议</span>: <Tooltip placement='topLeft' title={this.state.check_remark}>{this.state.check_remark}</Tooltip>
              </div>
            </Col>
          </Row>
        </Card>
        <Card title='案件还原' style={{ marginTop: '1rem' }}>
          <StrategyLogs data={this.state.strategyLogs} />
        </Card>
        <Card title='案件追踪' style={{ marginTop: '1rem' }}>
          <CaseTrace id={this.state.case_id} pageSize={3} case_node_id={this.state.case_node_id} />
        </Card>
        <Card title='案件核查' style={{ marginTop: '1rem' }}>
          {this.state.status === 2 && this.state.is_current_user_check ? (
            <div>
              <CustomForm
                closeModal={this.props.closeModal}
                createForm={(ref) => (this.form = ref)}
                formItems={formItems}
                onHandleSubmit={this.handleSubmit}
                colNum={1}
                hideSubmit={true}
              />
              <Row>
                <Col span={24} style={{ textAlign: 'center' }}>
                  <Button type='primary' onClick={this.selectCase}>
                    结案
                  </Button>
                  <Button onClick={this.distribute} className='marl10'>
                    分配
                  </Button>
                  <Button className='marl10' onClick={() => this.props.history.goBack()}>取消</Button>
                </Col>
              </Row>
            </div>
          ) : this.state.status === 1 || this.state.status === 2 ? (
            <Row style={{ lineHeight: '3' }}>
              <Col span={8}>
                <span>状态</span>: {this.state.status_name}
              </Col>
              <Col span={8}>
                <span>分配人</span>: {this.state.assigner_user_name}
              </Col>
              <Col span={8}>
                <span>分配时间</span>: {this.state.dispatch_time}
              </Col>
              <Col span={8}>
                <span>核查人</span>: {this.state.accepter_user_name}
              </Col>
              <Col span={24} style={{ textAlign: 'center' }}>
                <Button type='primary' onClick={() => this.props.history.goBack()}>取消</Button>
              </Col>
            </Row>
          ) : (
            <Row style={{ lineHeight: '3' }}>
              <Col span={8}>
                <span>状态</span>: {this.state.status_name}
              </Col>
              <Col span={8}>
                <span>核查人</span>: {this.state.case_end_user_name}
              </Col>
              <Col span={8}>
                <span>结案时间</span>: {this.state.case_end_time}
              </Col>
              <Col span={8}>
                <span>案件分类</span>: {this.state.case_category_name}
              </Col>
              <Col span={8}>
                <div className="overflowtext">
                  <span>结案意见</span>: <Tooltip placement='topLeft' title={this.state.check_remark}>{this.state.check_remark}</Tooltip>
                </div>
              </Col>
              <Col span={24} style={{ textAlign: 'center' }}>
                <Button type='primary' onClick={() => this.props.history.goBack()}>取消</Button>
              </Col>
            </Row>
          )}
        </Card>
      </div>
    );
  }
}

export default CaseDetail;
